/**
 * Created with JetBrains PhpStorm.
 * User: vander
 * Date: 5/28/13
 * Time: 7:59 PM
 * To change this template use File | Settings | File Templates.
 */
var Downloading = Class.create({
    initialize: function(){
        this.downloadingTask = new Array();

    },
    load: function(o){

    },
    add: function(bookInfo){
        var _this =  this;
        var bookId = bookInfo.bookId;
        var completed = 0;
        var total = 0;

        var liTag = new Element("li", {bookId: bookInfo.bookId});
        var img = $j("<img>").attr('src', Static.serverPath + bookInfo.resourcesPath + bookInfo.coverImage).attr({width: "80", height: "80"});
        var aTag = $j("<a></a>").append(img).append("<h3 class='ui-li-heading'>" + bookInfo.name + "</h3>");
        $j(aTag).append("<p>"+completed+"/"+total+" completed</p>");

        $j(liTag).append(aTag).appendTo("#" + Static.downloadingList);
        $j("#" + Static.downloadingList).listview('refresh');

        var rootDir;
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
            fileSystem.root.getDirectory(bookId, {create: true, exclusive: false}, function(parent){
                parent.getDirectory("resources", {create: true, exclusive: false}, function(res){
                    $j.getJSON(Static.serverPath + "getResourcesList.php", {bookId: bookId},done);
                }, fail)
                rootDir = fileSystem.root;
            }, fail);
        }, fail);

        function done(data){
            total = 1 + data.resources.length;

            $j(aTag).find("p").html(completed+"/"+total+" completed");
            $j("#" + Static.downloadingList).listview('refresh');

            new FileTransfer().download(Static.serverPath + data.definition,
                rootDir.fullPath + "/" + data.definition, success, fail);
            $j.each(data.resources, function(index, value){
                new FileTransfer().download(Static.serverPath + value,
                    rootDir.fullPath + "/" + value, success, fail);
            });
        }

        function success(){
            completed++;
            $j(aTag).find("p").html(completed+"/"+total+" completed");
            $j("#" + Static.downloadingList).listview('refresh');

            //Download finished
            if(completed == total){
                //Add to collections
                Global.collections.add(bookInfo);
            }
        }

        function fail(){
            console.log("FAIL request");
        }
    }
});
